/**
 * Created by shudong.msd(风骐) on 2016/4/9.
 */

'use strict';

app.controller('searchFilterBoxCtrl', ['$scope','$rootScope','$stateParams','$state', '$timeout','dataFetcher',function ($scope,$rootScope,$stateParams,$state,$timeout, dataFetcher) {

    function isJson(obj) {
        return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    }

    function filterCheckedItem(dict) {
        var res = [];
        for (var key in dict) {
            if (dict[key]) {
                res.push(key);
            }
        }
        return res;
    }

    $scope.resetData = function(){
        $state.reload('main.search.detail',{type:$stateParams.type});
    };

    $scope.stateType = $stateParams.type;
    sessionStorage.setItem('stateType',$stateParams.type);

    if($stateParams.type=='tv'){
        $scope.programType = '电视剧';
    }else{
        $scope.programType = '综艺节目';
    }

    //表单数据
    $scope.formData = {
        'sex':{},
        'ages':{},
        'cities':{},
        'tvTypes':{},
        'languages':{},
        'regions':{},
        'terminals':{},
        'stars':{},
        'channels':{},
        'startTime':"",
        'endTime':""
    };

    // 处理表单{terminals:{t:true,a:true},...}
    $scope.processForm = function () {
        var isValidate=true;
        for (var key in $scope.formData) {
            if (isJson($scope.formData[key])) {
                var dict = $scope.formData[key];
                var cnt = 0;

                if(key=='stars'){
                    if($.isEmptyObject($scope.formData['stars'])){
                        continue;
                    }
                }

                if($.inArray(key,['tvTypes','languages','regions'])!=-1){
                    var tmpNull = true;
                    for (var key0 in dict) {
                        if (dict[key0]) {
                            cnt++;
                            tmpNull = false;
                            break;
                        }
                    }
                    if(tmpNull){
                        $scope.selectAll(key);
                        cnt++;
                    }

                }else if($.inArray(key,['sex','ages','cities','terminals','channels'])!=-1){
                    var tmpNull = true;
                    for (var key0 in dict) {
                        if (dict[key0]) {
                            cnt++;
                            tmpNull = false;
                            break;
                        }
                    }
                    if(tmpNull){
                        //找到总体
                        for (var j in $scope[key]){
                            if($scope[key][j].name=='总体'){
                                $scope.formData[key][$scope[key][j].id]=true;
                                break;
                            }
                        }
                        cnt++;
                    }
                }else{
                    for (var key0 in dict) {
                        if (dict[key0]) {
                            cnt++;
                            break;
                        }
                    }
                }

                if(cnt==0){
                    isValidate = false;
                    break;
                }
            }else{
                if($scope.formData[key]==undefined||$scope.formData[key]==""){
                    isValidate = false;
                    break;
                }
            }
        }

        if(!isValidate){
            alert('请选择查询时间段');
            return;
        }

        for (var key in $scope.formData) {
            //if(formData[key] instanceof Object){
            if (isJson($scope.formData[key])) {
                //$scope.formData[key] = converDictToList($scope.formData[key],$scope[key]);
                $scope.formData[key] = filterCheckedItem($scope.formData[key]);
            }
        }

        var queryType = 1;
        if($stateParams.type=='tv'){
            queryType = 0;
        }

        var dealedForm = dataFetcher.proFormDetail($scope.formData,queryType);

        sessionStorage.setItem('searchData',JSON.stringify(dealedForm));

        $state.go('main.sResult.detail',{'type':$stateParams.type});


    };

    dataFetcher.initFilterData($scope,$stateParams.type);

    $scope.selectAll = function(name){
        if($scope.selectInfo[name]){
            $scope.formData[name]={};
            $scope.selectInfo[name] = false;
        }else{
            $scope.selectInfo[name] = true;
            for(var i in $scope[name]){
                $scope.formData[name][$scope[name][i].id] = true;
            }
        }
    };


    $scope.selectInfo = {
        'terminals':false,
        'channels':false,
        'tvTypes':false,
        'languages':false,
        'regions':false,
        'sex':false,
        'ages':false,
        'cities':false
    };

    // 初始化全选信息
    for(var key in $scope.selectInfo){
        if($scope.selectInfo[key]){
            for(var i in $scope[key]){
                $scope.formData[key][$scope[key][i].id] = true;
            }
        }
    }


    $scope.checkSelectAll = function(name){
        var count = 0;

        for(var key in $scope.formData[name]){
            if($scope.formData[name][key])count++;
        }
        if(count==$scope[name].length){
            $scope.selectInfo[name] = true;
        }else{
            $scope.selectInfo[name] = false;
        }
    };

    $scope.$on('$viewContentLoaded',function(){
        $(".term-list-table .term-list-content.mz-datepicker input").datepicker({
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose:true,
            minView:2,
            keyboardNavigation:true,
            endDate:'0d',
            immediateUpdates:true,
            orientation:"bottom auto",
            todayHighlight:true,
            weekStart:1,
            fqInputs: $(".term-list-table .term-list-content.mz-datepicker input"),
            arrowTemplates: {
                leftArrow: '<b class="fa fa-long-arrow-left">&lt;</b>',
                rightArrow: '<b class="fa fa-long-arrow-left">&gt;</b>'
            }
        });
    });



    $scope.citiesDynamicDom = new dynamicDom({
        source: null,
        target: null,
        resultTitle : null,
        targetItemClass : "list-group-item list-category_item selected-city",
        removeButton : null
    });

    $scope.starsDynamicDom = new dynamicDom({
        source: null,
        target: null,
        resultTitle :  null,
        targetItemClass : "list-group-item list-category_item selected-star",
        removeButton : null
    });

    var cityInit = false;
    var starInit = false;
    var comutil = new commUtils();

    $scope.initAction=function(type) {

        if(type=='city'){
            if(cityInit)return;
            cityInit = true;
            //模态框 字母列表
            $(".mz-search-filterbox .alphabet-list li a").unbind('click');
            $(".mz-search-filterbox .alphabet-list li a").click(function(){
                if(!$(this).hasClass("alphabet-selected")){
                    $(this).addClass("alphabet-selected");
                    $(".mz-search-filterbox .alphabet-list li a").not(this).removeClass("alphabet-selected")
                }
            });
            //************************城市model部分
            $scope.citiesDynamicDom.setTarget($(".selected-cities"));
            $scope.citiesDynamicDom.setResultTitle($(".city-result-title span"));
            $scope.citiesDynamicDom.setRemoveButton($(".remove-all-cities"));


            //城市选择搜索框
            //var cites = ['北京','上海','杭州','北海','北极'];

            var citesBlood = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                //local: cites,
                //prefetch: '本地数据.json',//速度快
                remote: {
                    url: UrlMappings.REGION_KEYWORD_SEARCH+'?q=%QUERY&access_token='+comutil.getTocken(),
                    wildcard:'%QUERY'
                }
            });
            var cityTypeahead = $('.search-region-group .typeahead').typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1
                },
                {
                    name: 'cities-data',
                    display : 'name',
                    source: citesBlood,
                    limit: 5
                }
            );
            //绑定选择后以及焦点改变时发生的事件
            cityTypeahead.bind('typeahead:select', function(ev, suggestion) {
                //选择该城市
                $scope.citiesDynamicDom.addToTarget(suggestion.name);
            });

            $('.choose-city-footer button:first-of-type').off('click');
            $('.choose-city-footer button:first-of-type').on('click', function () {
                $scope.citiesDynamicDom.removeAllSelect();
            });

            $scope.selectAllCity = function($event){
                if($scope.selectInfo['cities']){
                    $scope.selectInfo['cities'] = false;
                    $timeout(function() {
                        for (var i in $scope['hotCities']) {
                            //$scope.formData['cities'][$scope['hotCities'][i]]=false;
                            if ($scope.formData['cities'][$scope['hotCities'][i].id]) {
                                // citiesDynamicDom.toggleChecked($scope['hotCities'][i]);
                                $scope.citiesDynamicDom.removeTargetDir($scope['hotCities'][i].name);
                            }
                        }
                    });
                }else{
                    $scope.selectInfo['cities'] = true;
                    $timeout(function(){
                        for(var i in $scope['hotCities']){
                            //$scope.formData['cities'][$scope['hotCities'][i]]=true;
                            if(!$scope.formData['cities'][$scope['hotCities'][i].id]){
                                $scope.citiesDynamicDom.addToTarget($scope['hotCities'][i].name);
                            }
                        }
                    });

                }
            };

            $scope.checkSelectAllCity = function(){
                var count = 0;
                for(var key in $scope.formData['cities']){
                    if($scope.formData['cities'][key]){
                        for(var j in $scope['hotCities']){
                            if($scope['hotCities'][j].id==key){
                                count++;
                                break;
                            }
                        }
                    }
                }
                if(count==$scope['hotCities'].length){
                    $scope.selectInfo['cities'] = true;
                }else{
                    $scope.selectInfo['cities'] = false;
                }
            }


        }else{
            if(starInit)return;
            starInit = true;
            //************************明星model部分
            //模态框 字母列表
            $(".mz-search-filterbox .alphabet-list li a").unbind('click');
            $(".mz-search-filterbox .alphabet-list li a").click(function(){
                if(!$(this).hasClass("alphabet-selected")){
                    $(this).addClass("alphabet-selected");
                    $(".mz-search-filterbox .alphabet-list li a").not(this).removeClass("alphabet-selected")
                }
            });

            $("#starTab > li:last-of-type").focus();

            $timeout(function(){
                $("#starTab > li:first-of-type a").trigger('click');
            },0);


            $scope.starsDynamicDom.setTarget($(" .selected-stars"));
            $scope.starsDynamicDom.setResultTitle( $(".star-result-title span"));
            $scope.starsDynamicDom.setRemoveButton($(".remove-all-stars"));



            var starsBlood = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                //local: stars,
                //prefetch: '本地数据.json',//速度快
                remote: {
                    url: UrlMappings.STAR_KEYWORD_SEARCH+'?q=%QUERY&access_token='+comutil.getTocken(),
                    wildcard:'%QUERY'
                }
            });

            var starTypeahead = $('.search-star-group .typeahead').typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1
                },
                {
                    name: 'cities-data',
                    source: starsBlood,
                    display:'name',
                    limit: 5
                }
            );

            //var stars = ['张杰','张学友','张三丰'];

            //绑定选择后以及焦点改变时发生的事件
            starTypeahead.bind('typeahead:select', function(ev, suggestion) {
                //选择该城市
                $scope.starsDynamicDom.addToTarget(suggestion.name);
            });

            $('.choose-star-footer button:first-of-type').off('click');
            $('.choose-star-footer button:first-of-type').on('click', function () {
                $scope.starsDynamicDom.removeAllSelect();
            })

        }

    };


    $scope.initStarTab = function(starType){
        if(!$.isEmptyObject($scope.starDetails[starType]))return;
        $scope.starDetails[starType] = dataFetcher.getStarDetail(starType);
    }



    sessionStorage.setItem('whereIam','search');

}]);